#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年2月17日

@author: Administrator
'''
import copy
import datetime
from functools import wraps

from django.contrib import auth
from django.http import HttpResponse, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.decorators import available_attrs
from django.utils.http import urlquote

from common import settings
from common.utils import sign
import ujson as json


def unlogin_required(view_func):
    """ 要求未登录 """
    def _check_login(request, *args, **kwargs):
#        if request.hasattr(request,"user"):
        if request.user.is_authenticated():
#            auth.logout(request)
            return HttpResponseRedirect(settings.LOGIN_SUCESS_URL)
        return view_func(request, *args, **kwargs)

    return _check_login

def login_required(view_func):
    """Simplified version of auth.decorators.login_required,
       which works with our LOGIN_URL and removes the 'next'
       parameter which we don't need yet.
    """
    def wrapped_view(request, *args, **kwargs):
        if request.session.has_key(auth.SESSION_KEY) \
                and request.session.has_key(auth.BACKEND_SESSION_KEY) \
                and (request.session[auth.BACKEND_SESSION_KEY] in settings.AUTHENTICATION_BACKENDS):
            return view_func(request, *args, **kwargs)
        else:
            if request.is_ajax():
                response = HttpResponse(json.dumps(settings.ERROR['NOT_LOGIN_ERR']),
                                        mimetype='application/json')
            else:
                response = HttpResponseRedirect('%s?next=http://%s%s' % \
                                                (settings.LOGIN_URL, request.META['HTTP_HOST'],
                                                 urlquote(request.get_full_path())))
            response.delete_cookie(settings.USERINFO_COOKIE_NAME, domain=settings.SESSION_COOKIE_DOMAIN)
            return response

    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)


def verify_signature(view_func):
    """
    校验签名
    """
    def wrapped_view(request, *args, **kwargs):
        rsp_data = copy.copy(settings.ERROR['SUCC'])
        try:
            if request.method == 'GET':
                # 验证签名是否正确
                sign_keys = list(request.GET.keys())
                sign_keys.remove('sign')
                params = {}
                for k in sign_keys:
                    params[k] = request.GET[k]
                if not sign.verify_sign(params, settings.OPEN_KEY, request.GET['sign']):
                    rsp_data = copy.copy(settings.ERROR['PERM_ERR'])
                    rsp_data['msg'] = u'签名错误'
                    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

            if request.method == 'POST':
                # 验证签名是否正确
                sign_keys = list(request.POST.keys())
                sign_keys.remove('sign')
                params = {}
                for k in sign_keys:
                    params[k] = request.POST[k]
                if not sign.verify_sign(params, settings.OPEN_KEY, request.POST['sign']):
                    rsp_data = copy.copy(settings.ERROR['PERM_ERR'])
                    rsp_data['msg'] = u'签名错误'
                    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

        except:
            rsp_data = copy.copy(settings.ERROR['PARA_ERR'])
            return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

        return view_func(request, *args, **kwargs)
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
